package com.yibo.manager.base.handler;

import com.yibo.support.helper.JsonHelper;
import com.yibo.support.helper.ObjectHelper;
import com.yibo.support.pojo.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.yibo.support.constant.ApiUrlConstant.PUBLIC_URL;

@Component
public class MvcInterceptor implements HandlerInterceptor {

    @Override
    @SuppressWarnings("unchecked")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //接口地址
        String path = request.getServletPath();

        if(path.contains("/login") || path.contains("/login.html") || path.contains(PUBLIC_URL) ){
            return true;
        }

        String sessionId = request.getHeader("token");
        try {
            String userId = System.getProperty(sessionId);
            if(ObjectHelper.isEmpty(userId)){
                response.getWriter().write(JsonHelper.toJson(new Result<>(-120,"need login",null)));
                return false;
            }
        }catch (Exception e){
            response.getWriter().write(JsonHelper.toJson(new Result<>(-120,"need login",null)));
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
